<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2022/02/10} {15:51} 
 */

namespace wanghua\general_utility_tools_php\encrypt;


/**
 * 3DES,三重数据加密算法
 *
 * Class TripleDES
 * @package wanghua\general_utility_tools_php\encrypt
 */
class TripleDES
{


    /**
     * desc：加密
     *
     * author：wh
     * @param string $value
     * @param $key
     * @return string
     */
    public function encrypt(string $value, $key)
    {
        $value = self::PaddingPKCS7($value);
        //AES-128-ECB|不能用 AES-256-CBC|16 AES-128-CBC|16 BF-CBC|8 aes-128-gcm|需要加$tag  DES-EDE3-CBC|8
        $cipher = "DES-EDE3";
//        if (in_array($cipher, openssl_get_cipher_methods())) {}
        $result = openssl_encrypt($value, $cipher, $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, "");
        return base64_encode($result);
    }

    /**
     * @title 解密
     *
     * @param string $str 要传的参数
     * @param $key
     * @return bool|false|string
     *
     */
    public function decrypt(string $str, $key)
    {
        $decrypted = openssl_decrypt(base64_decode($str), 'DES-EDE3', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, "");
        $ret = self::UnPaddingPKCS7($decrypted);
        return $ret;
    }

    /**
     * desc：
     * author：wh
     * @param $data
     * @return string
     */
    private function PaddingPKCS7($data)
    {
        //$block_size = mcrypt_get_block_size('tripledes', 'cbc');//获取长度
        //$block_size = openssl_cipher_iv_length('tripledes', 'cbc');//获取长度
        $block_size = 8;
        $padding_char = $block_size - (strlen($data) % $block_size);
        $data .= str_repeat(chr($padding_char), $padding_char);
        return $data;
    }

    /**
     * desc：
     * author：wh
     * @param $text
     * @return false|string
     */
    private function UnPaddingPKCS7($text)
    {
        $pad = ord($text{strlen($text) - 1});
        if ($pad > strlen($text)) {
            return false;
        }
        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
            return false;
        }
        return substr($text, 0, -1 * $pad);
    }
}